package org.jground.rx.ui.zk.docu;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jground.dbfs.IDBFile;
import org.jground.rx.RXView;
import org.jground.rx.docu.DocuUtils;
import org.jground.rx.ui.zk.UIFrame;
import org.jground.rx.ui.zk.viewControl.UIAttributeViewBase;
import org.jground.util.ArrayUtils;
import org.jground.util.ImagingUtils;
import org.jground.util.StringUtils;
import org.jground.zk.zulX.BoxX;
import org.jground.zk.zulX.ZK;
import org.zkoss.zul.Image;
import org.zkoss.zul.Label;
import org.zkoss.zul.impl.XulElement;

public class UIAttributeViewDocu extends UIAttributeViewBase {

    /**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static Log logger = LogFactory.getLog(UIAttributeViewDocu.class);

    public UIAttributeViewDocu createNew(UIFrame uiFrame, RXView moView) {
        return new UIAttributeViewDocu(uiFrame, moView);
    }

    public UIAttributeViewDocu() {}

    private XulElement docuElement;
    private BoxX box;
    private String filename;
    private boolean isPicture;
    private UIImageView uiImageView;
    private UIFileDownload2 uiFileDownload;

    private UIAttributeViewDocu(UIFrame uiFrame, RXView moView) {
        super(uiFrame, moView);
        logger.debug("init UIAttributeViewDocu");
        isPicture = "picture".equals(moView.getWidgetHint());
        uiImageView = new UIImageView();
        uiFileDownload = new UIFileDownload2();
        box = new BoxX();
        box.setOrient(ZK.AttValue.horizontal);
        box.setAlign("end");
        // box.setValign(ZK.AttValue.bottom);
        box.setSpacing("8px");
        //
        add(box);
    }

    public void set(String... values) {
        clear();
        if (ArrayUtils.isNotEmpty(values) && StringUtils.isNotEmpty(values[0])) {
            filename = values[0];
            long oid = getDataContext().getOid();
            IDBFile file = DocuUtils.getFile(oid, filename);
            uiFileDownload.setFile(file);
            if (isPicture && ImagingUtils.isExtensionSupported(filename)) {
                Image icon = new Image();
                icon.setContent(UIDocuUtils.getImage(oid, UIAttributeControlDocu.SMALL_HEIGHT,  filename));
                docuElement = icon;
                //
                uiImageView.setAImageFile(file);
                //
                box.set(docuElement, uiFileDownload, uiImageView);
            } else {
                docuElement = new Label(filename);
                box.set(uiFileDownload);
            }

        }
    }

    public void clear() {
        box.removeAll();
    }

}
